﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Text;

namespace park.System_Manager
{
    public partial class AuthorityAgencyArea : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTree();
                string id = Request.QueryString["id"];

                if (!string.IsNullOrEmpty(id))
                {
                    cn.linkit.epark.ServiceList sl = new cn.linkit.epark.ServiceList();
                    
                    //string areaList = sl.ListAreaAuthority();// 区域权限列表
                    //string agencyAreaInfo = sl.GetAgencyAreaById(id);

                    string areaList = "{\"ListAreaAuthority\":[{\"id\":1,\"AreaName\":\"武昌\",\"StreetList\":[{\"StreetId\":101,\"StreetName\":\"中南\"},{\"StreetId\":102,\"StreetName\":\"徐东\"},{\"StreetId\":103,\"StreetName\":\"光谷\"}]},{\"id\": 2,\"AreaName\": \"汉口\",\"StreetList\":[{\"StreetId\":204,\"StreetName\":\"桥口\"},{\"StreetId\":205,\"StreetName\":\"江岸\"}]}]}";
                    string agencyAreaInfo = "{\"id\":1,\"Name\":\"汉口巡检中心\",\"AreaAuthority\":\"1,2,103,205\"}";

                    ViewState.Add("areaList", areaList);

                    LoadPageInfo(areaList,agencyAreaInfo);
                }

            }
        }

        private void BindTree()
        {
            cn.linkit.epark.ServiceList sl = new cn.linkit.epark.ServiceList();

            //string json = sl.SearchAgency(-1,-1,"");
            string json = "{\"data\":["
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":-1,\"id\":2,\"code\":\"YHX3678\",\"name\":\"硚口设备总站\",\" hasAutority\":1,\"order\":1024},"
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":2,\"id\":3,\"code\":\"YHX3679\",\"name\":\"硚口设备分站1\",\" hasAutority\":1,\"order\":1024},"
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":3,\"id\":10,\"code\":\"YHX3679-1\",\"name\":\"硚口设备分站1设备处1\",\"hasAutority\":1,\"order\":1024},"
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":2,\"id\":5,\"code\":\"YHX367a\",\"name\":\"硚口设备分站2\",\" hasAutority\":1,\"order\":2048},"
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":-1,\"id\":4,\"code\":\"YHX3678\",\"name\":\"硚口设备总站2\",\" hasAutority\":1,\"order\":1024},"
                + "{\"cName\":\"汉口\",\"rName\":\"硚口\",\"pid\":4,\"id\":13,\"code\":\"YHX3678\",\"name\":\"硚口设备总站3\",\" hasAutority\":1,\"order\":1024}"
                + "]}";

            JObject obj = JObject.Parse(json);

            var s = from p in obj["data"].Where(t => { return t["pid"].ToString() == "-1"; })
                    select p;

            foreach (var item in s)
            {
                TreeNode tr = new TreeNode(item["name"].ToString(), item["id"].ToString());
                tr.NavigateUrl = "?id=" + item["id"].ToString();
                this.tree_Agency.Nodes.Add(tr);
                AddTreeNode(tr, item["id"].ToString(), obj);
            }
        }

        private void AddTreeNode(TreeNode currentNode, string pid, JObject obj)
        {
            var s = from p in obj["data"].Where(t => { return t["pid"].ToString() == pid; })
                    select p;
            foreach (var item in s)
            {
                TreeNode tr = new TreeNode(item["name"].ToString(), item["id"].ToString());
                tr.NavigateUrl = "?id=" + item["id"].ToString();
                currentNode.ChildNodes.Add(tr);
                AddTreeNode(tr, item["id"].ToString(), obj);
            }
        }


        private void LoadPageInfo(string areaList,string agencyAreaInfo)
        {
            JObject areaListObj = JObject.Parse(areaList);
            JObject agencyAreaInfoObj = JObject.Parse(agencyAreaInfo);

            this.ltName.Text = agencyAreaInfoObj["Name"].ToString();
            this.hdf_AreaAuthority.Value = agencyAreaInfoObj["AreaAuthority"].ToString();
            string areaAuthority = "," + agencyAreaInfoObj["AreaAuthority"].ToString() + ",";

            StringBuilder sbAreaList = new StringBuilder();

            for (int i = 0; i < areaListObj["ListAreaAuthority"].Count(); i++)
            {
                string areaChecked = string.Empty;

                string areaId = areaListObj["ListAreaAuthority"][i]["id"].ToString();

                
                areaChecked = areaAuthority.Contains("," + areaId + ",")?"checked=\"checked\"":string.Empty;

                sbAreaList.AppendFormat("\r\n<div><label><input type=\"checkbox\" value=\"{0}\" onclick=\'AreaClick(\"{0}\",this.checked)\' {2}/>{1}</label></div>\r\n",
                    areaId,
                    areaListObj["ListAreaAuthority"][i]["AreaName"].ToString(), areaChecked);

                if (areaListObj["ListAreaAuthority"][i]["StreetList"].Count() > 0)
                {
                    sbAreaList.AppendFormat("<div>\r\n\t<ul id=\"ul_street_{0}\">\r\n", areaId);
                    for (int j = 0; j < areaListObj["ListAreaAuthority"][i]["StreetList"].Count(); j++)
                    {
                        string streetId = areaListObj["ListAreaAuthority"][i]["StreetList"][j]["StreetId"].ToString();
                        areaChecked = areaAuthority.Contains("," + streetId + ",") ? "checked=\"checked\"" : string.Empty;

                        sbAreaList.AppendFormat("\t\t<li><label><input type=\"checkbox\" value=\"{0}\" onclick=\"StreetClick()\" {2}/>{1}</label></li>\r\n",
                            streetId,
                            areaListObj["ListAreaAuthority"][i]["StreetList"][j]["StreetName"].ToString(), areaChecked);
                    }
                    sbAreaList.Append("\t</ul>\r\n</div>");
                }
                sbAreaList.Append("<div style=\"clear:both;\"></div>");
            }
            this.ltAreaList.Text = sbAreaList.ToString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(id))
            {
                string name = this.ltName.Text;
                string areaAuthority = this.hdf_AreaAuthority.Value.Trim(',');

                string agencyAreaInfo = "{" + string.Format("\"id\":{0},\"Name\":\"{1}\",\"AreaAuthority\":\"{2}\"", id, name, areaAuthority) + "}";

                cn.linkit.epark.ServiceList sl = new cn.linkit.epark.ServiceList();

                // bool flag = sl.UpdateAgencyArea(agencyAreaInfo);
                bool flag = true;

                string msg = flag ? "数据保存成功！" : "数据保存失败，请重试...";

                string areaList = ViewState["areaList"].ToString();
                LoadPageInfo(areaList, agencyAreaInfo); // 根据用户选择重新加载区域权限选择结果

                Page.ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), "<script>alert('" + msg + "');</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), "<script>alert('您还没有选择任何机构，请先选择要修改的机构。');</script>");
            }
        }

    }
}